/**
 * 
 */
package com.testvideo.util;

import java.io.IOException;
import java.io.Reader;

/**
 * @author Administrator
 *
 */
public class NoDelayReader extends Reader {
	
	protected Reader underlyReader ;
	private String buffer = new String() ;
	private Object lock = new Object() ;
	
	private ReaderThread readerThread ;
	
	public NoDelayReader(Reader underlyReader){
		this.underlyReader = underlyReader ;
		readerThread = new ReaderThread() ;
		
		readerThread.start() ;
	}
	
	public void clearBuffer(){
		synchronized (lock) {
			buffer = new String() ;
		}
	}

	public void close() throws IOException {
		if(readerThread != null){
			readerThread.quit() ;
		}
		
		if(underlyReader != null){
			underlyReader.close() ;
		}
	}

	public int read(char[] cbuf, int off, int len) throws IOException {
		int j = 0 ;
		
		synchronized (lock) {
			int b_length = buffer.length() ;
			if(b_length <= 0) return -1 ;			
			
			for(int i = off ; i < len && j <b_length ; i++, j++){
				cbuf[i] = buffer.charAt(j) ;
			}
			
			if(j >= b_length){ //全部读取完毕了。
				buffer = new String() ;
			}else{
				buffer = buffer.substring(j) ;
			}			
		}
		
		return j ;
	}
	
	private class ReaderThread extends Thread{
		
		private boolean keepRunning = true ;
		
		public void run(){
			while(keepRunning){
				int i_char = -1 ;
				
				try {
					i_char = underlyReader.read();
				} catch (Exception e) {
					
				}
				
				if(i_char > 0){
					synchronized (lock) {
						buffer = buffer + (char)i_char ;
					}
				}
			}			
		}
		
		public void quit(){
			keepRunning = false ;
		}
		
	}

}
